#!/usr/bin/python
# coding=utf-8

import sys
import argparse
import logging

from utils.daemon import Daemon
from mitmproxy import flow, proxy, controller, options
from mitmproxy.proxy.server import ProxyServer
from utils.parser import ResponseParser, save_cnf, read_cnf
from utils.handle import wyproxy_request_handle, wyproxy_response_handle

logging.basicConfig(
    level=logging.INFO, # filename='/tmp/wyproxy.log',
    format='%(asctime)s [%(levelname)s] %(message)s',
)

class my_proxy(flow.FlowMaster):

    def __init__(self,opts, server, state):
        super(my_proxy, self).__init__(opts, server, state)

    def run(self):
        try:
            logging.info("MyProxy started successfully...")
            flow.FlowMaster.run(self)
        except KeyboardInterrupt:
            self.shutdown()
            logging.info("Ctrl C - stopping wyproxy server")

    @controller.handler
    def request(self, f):
        f.request.anticache()  # disable cache
        f.request.anticomp()  # disable gzip compress
        f.request.headers['X-Online-Host'] = 'wap.gd.10086.cn'
        logging.info("请求开始 %s",f.request.host)

    @controller.handler
    def response(self, f):
        logging.info("返回响应")
        f.response.headers['my-hread'] = 'test-head'


def run():
    port = 9090
    mode = 'regular'
    opts = options.Options(
        listen_port=port,
        mode=mode,
        cadir="../ssl/",
    )

    config = proxy.ProxyConfig(opts)
    state = flow.State()
    server = ProxyServer(config)
    m = my_proxy(opts, server, state)
    m.run()


if __name__ == '__main__':
    run()